import React, { useState } from 'react';
import { Button, Layout, Result, Space } from 'antd';
import { MenuUnfoldOutlined, MenuFoldOutlined } from '@ant-design/icons';
import '@ant-design/pro-layout';
import style from './style.module.less';
import Menu, { getSelectedMenuKey } from './menu';
import { Scrollbars } from 'react-custom-scrollbars';

import routes from '@/routes';
import AvatarDropdown from '@/components/RightContent/AvatarDropdown';
import { useModel } from '@@/plugin-model/useModel';
import { ke } from '@/plugins/ke';
import { Access, useAccess } from '@@/plugin-access/access';
import { history } from 'umi';

export default (props: any) => {
  const { initialState } = useModel('@@initialState');
  const access = useAccess();
  const [collapsed, setCollapsed] = useState<boolean>(false);

  const current = getSelectedMenuKey(history.location.pathname, props.routes);
  return (
    <Layout>
      <Layout.Sider
        trigger={null}
        style={{
          position: 'fixed',
          zIndex: 10,
          left: 0,
          transition: 'none',
        }}
        collapsed={collapsed}
        collapsible
      >
        <div className={style.logo}>
          <div className={'logo-title'}>
            <img src={ke.textToAvatar(initialState?.title ?? '')} />
          </div>

          {!collapsed ? initialState?.title : ''}
        </div>

        <Scrollbars className={style.sidebar}>
          <div>
            <Menu routes={routes} collapsed={collapsed} />
          </div>
        </Scrollbars>
      </Layout.Sider>

      <Layout
        className={style.layout}
        style={{ marginLeft: collapsed ? 80 : 200 }}
      >
        <Layout.Header
          className={style.header}
          style={{ left: collapsed ? 80 : 200 }}
        >
          {React.createElement(
            collapsed ? MenuUnfoldOutlined : MenuFoldOutlined,
            {
              className: 'trigger',
              onClick: () => {
                setCollapsed(!collapsed);
              },
            },
          )}

          <Space className={style.right}>
            <AvatarDropdown />
          </Space>
        </Layout.Header>

        <Layout.Content className={style.content}>
          <Access
            accessible={access.canPermission(current.access)}
            fallback={
              <Result
                status="403"
                title="403"
                subTitle="你没有此页面的访问权限。"
                extra={
                  <Button type="primary" onClick={() => history.goBack()}>
                    返回上级
                  </Button>
                }
              />
            }
          >
            {props.children}
          </Access>
        </Layout.Content>
      </Layout>
    </Layout>
  );
};
